<template>
  <el-drawer
    v-model="dialogFormVisible"
    :title="title"
    direction="rtl"
    size="60%"
    :before-close="close"
  >
    <template #default>
      <vxe-grid
        ref="userRoleGrid"
        border
        stripe
        resizable
        keep-source
        auto-resize
        sync-resize
        height="auto"
        :loading="listLoading"
        :column-config="{ resizable: true }"
        :export-config="{}"
        :columns="tableColumn"
        align="center"
        :checkbox-config="{
          highlight: true,
          reserve: true,
          checkRowKeys: defaultCheckedKeys,
        }"
        :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
        :seq-config="{ seqMethod: seqMethod }"
        :edit-rules="rules"
        :edit-config="{
          trigger: 'click',
          enabled: true,
          mode: 'cell',
          immediate: true,
        }"
      >
        <template #form>
          <vxe-form
            ref="queryform"
            title-align="right"
            title-width="150"
            prevent-submit
          >
            <vxe-form-item title="帐号" span="8">
              <template #default>
                <el-input
                  v-model="queryForm.username"
                  placeholder="帐号"
                  style="width: 150px"
                  clearable
                />
              </template>
            </vxe-form-item>
            <vxe-form-item title="昵称" span="8">
              <template #default>
                <el-input
                  v-model="queryForm.nickname"
                  placeholder="请输入昵称"
                  style="width: 150px"
                  clearable
                />
              </template>
            </vxe-form-item>
            <vxe-form-item span="24" align="center">
              <div class="dialog-footer" style="text-align: center">
                <el-button :icon="Search" type="primary" @click="fetchData">
                  查询
                </el-button>
              </div>
            </vxe-form-item>
          </vxe-form>
        </template>
        <template #dataPermission="{ row }">
          <el-select
            v-model="row.dataPermission"
            placeholder="请选择数据权限"
            popper-class="vxe-table--ignore-clear"
            @change="refreshData(row)"
          >
            <el-option
              v-for="item in dataPermissionOptions"
              :key="item.type"
              :label="item.remarks"
              :value="item.type"
            />
          </el-select>
        </template>
        <template #dataPermissionV="{ row }">
          {{ dataPermissionOptionsV(row) }}
        </template>
      </vxe-grid>
    </template>
    <template #footer>
      <el-pagination
        background
        :current-page="queryForm.page"
        :layout="layout"
        :page-size="queryForm.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </template>
  </el-drawer>
</template>

<script>
  import { Search } from '@element-plus/icons-vue'
  import { postAction } from '@/api/requestEvents'
  import { getRoleUserPage } from '@/api/system/user/index'

  export default defineComponent({
    name: 'UserRoleEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const $XEUtils = inject('$XEUtils')
      const state = reactive({
        dialogFormVisible: false,
        userRoleGrid: 'userRoleGrid',
        listLoading: false,
        rules: {
          nickName: [{ required: true, message: '请选择数据权限' }],
          dataPermission: [{ required: true, message: '请选择数据权限' }],
        },
        tableColumn: [
          { type: 'checkbox', width: 50, fixed: 'left' },
          { type: 'seq', title: '序号', width: 50, fixed: 'left' },
          {
            title: '所属单位',
            width: 200,
            field: 'unitName',
          },
          {
            title: '部门',
            width: 130,
            field: 'deptName',
          },
          {
            title: '用户昵称',
            field: 'nickname',
            width: 120,
          },
          {
            title: '帐号',
            width: 120,
            field: 'username',
          },
          {
            title: '数据权限',
            field: 'dataPermission',
            width: 260,
            fixed: 'right',
            editRender: {
              enabled: true,
              autoselect: true,
              autofocus: '.el-input__inner',
            },
            slots: { default: 'dataPermissionV', edit: 'dataPermission' },
          },
        ],
        title: '',
        defaultCheckedKeys: [],
        dataPermissionOptions: [],
        orgData: [],
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          pageNo: 1,
          pageSize: 30,
          roleId: '',
          username: '',
          nickname: '',
        },
      })

      const showEdit = async (row) => {
        state.dialogFormVisible = true
        if (row) {
          state.title = `当前角色：${row.name}`

          state.listLoading = true
          state.queryForm.roleId = row.id
          const userRoleData = await getRoleUserPage(state.queryForm).catch(
            (err) => {
              state.listLoading = false
            }
          )
          if (userRoleData.code === 0 || userRoleData.code === 200) {
            state['userRoleGrid'].reloadData(userRoleData.data.list)
            state.total = userRoleData.data.total
            state.listLoading = false
          } else {
            $baseMessage(userRoleData.msg, 'error', 'vab-hey-message-success')
          }
        }
      }
      const close = () => {
        state.form = {
          pageNo: 1,
          pageSize: 30,
          roleId: '',
          username: '',
          nickname: '',
        }
        state.dialogFormVisible = false
      }

      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }

      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }

      const seqMethod = ({ row, rowIndex, column, columnIndex }) => {
        return (
          (state.queryForm.pageNo - 1) * state.queryForm.pageSize + rowIndex + 1
        )
      }

      const fetchData = async () => {
        state.listLoading = true
        state.defaultCheckedKeys = []
        const userRoleData = await getRoleUserPage(state.queryForm).catch(
          (err) => {
            state.listLoading = false
          }
        )
        state.queryForm.pageNo = 1
        if (userRoleData.code === 0 || userRoleData.code === 200) {
          state['userRoleGrid'].reloadData(userRoleData.data.list)
          state.total = userRoleData.data.total
          state.listLoading = false
        } else {
          $baseMessage(userRoleData.msg, 'error', 'vab-hey-message-success')
        }
      }

      const handleSave = async () => {
        const xTableValidate = await state.userRoleGrid.validate(true)
        if (!xTableValidate) {
          state.listLoading = true
          const fullData = state.userRoleGrid.getCheckboxRecords()
          const userData = []
          if (fullData.length > 0) {
            fullData.forEach((item) => {
              userData.push({
                userId: item.id,
                roleId: state.queryForm.roleId,
                dataPermission: item.dataPermission,
              })
            })
            const userRoleData = await postAction(
              '/api/system/user/updateUserRole',
              { selectRolesByNewUser: userData }
            )
            if (userRoleData.code === 200) {
              emit('fetch-data')
              close()
            } else {
              $baseMessage(
                userRoleData.message,
                'success',
                'vab-hey-message-success'
              )
            }
            state.listLoading = false
          }
        }
      }

      const dataPermissionOptionsV = (row) => {
        let type = ''
        state.dataPermissionOptions.forEach((item) => {
          if (item.id == row.dataPermission) {
            type = item.remarks
          }
        })
        return type
      }

      const refreshData = (row) => {
        //console.log(row)
      }

      onMounted(() => {
        //fetchData()
      })
      return {
        ...toRefs(state),
        handleSizeChange,
        handleCurrentChange,
        showEdit,
        close,
        fetchData,
        handleSave,
        seqMethod,
        Search,
        dataPermissionOptionsV,
        refreshData,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .vab-tree-border {
    width: 100%;
    height: 250px;
    padding: $base-padding;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: $base-border-radius;
  }

  .el-container {
    height: calc(100vh - 155px);
  }
</style>
